package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.SQLException;

import net.sf.json.JSONObject;
import DBConnection.DB;

public class getCollegeCity {

	static DB db = new DB();

	/**
	 * 获取仪器所在地的城市名称
	 * 
	 * @param add
	 *            详细地址
	 * @param lat
	 *            城市纬度
	 * @param ln
	 *            'g 城市经度
	 * @return 仪器所在地的城市名称
	 * @throws SQLException
	 */
	public static String getCity(String add, String lat, String lng) {
		String url;
		String City = "";
		String KEY = "";
		url = "http://api.map.baidu.com/geocoder/v2/?location=" + lat + ","
				+ lng + "&output=json&ak=" + KEY;
		String json = loadJSON(url);
		JSONObject obj = JSONObject.fromObject(json);
		if (obj.get("status").toString().equals("0")
				&& !obj.getString("result").equals("[]")) {
			City = obj.getJSONObject("result")
					.getJSONObject("addressComponent").getString("city");
		}
		String sqlQuery = "update researchorg set city = '" + City
				+ "' where address = '" + add + "' ;";
		System.out.println(sqlQuery);
		return City;

	}

	public static String loadJSON(String url) {
		StringBuilder json = new StringBuilder();
		try {
			URL oracle = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) oracle
					.openConnection();
			connection.setConnectTimeout(5000);

			// 若连接失败，则重新连接
			while (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
				try {
					Thread.sleep(500);
					connection = (HttpURLConnection) oracle.openConnection();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				;
			}
			BufferedReader in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String inputLine = null;
			while ((inputLine = in.readLine()) != null) {
				json.append(inputLine);
			}
			in.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return json.toString();
	}

}
